<template>
  <PageWrapper v-loading="loading" loading-tip="加载中...">
    <div class="p-4 p-4-tag">
      <div class="tag">
        <BasicTable @register="registerTable">
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
              <TableAction
                :actions="[
                  {
                    label: '应答告警',
                    ifShow: hasPermission('7-1-2-respondAlarm'),
                    icon: 'ant-design:setting-outlined',
                    onClick: handleSet.bind(null, record),
                  },
                  {
                    label: '远程诊断',
                    ifShow: hasPermission('7-1-2-respondAlarm'),
                    icon: 'ant-design:setting-outlined',
                    onClick: openRouter.bind(null, record),
                  },
                ]"
              />
            </template>
          </template>
          <template #toolbar>
            <a-input-search
              v-model:value="searchValue"
              placeholder="告警记录查询"
              style="width: 300px"
              :allowClear="true"
              @search="onSearch"
            />
            <a-button type="primary" @click="onSearch"> 刷新 </a-button>
          </template>
        </BasicTable>
      </div>
    </div>
  </PageWrapper>
</template>

<script setup lang="ts">
  import { usePermission } from '/@/hooks/web/usePermission';
  import { PageWrapper } from '/@/components/Page';
  import { BasicTable, TableAction, useTable } from '/@/components/Table';
  import { BasicColumn } from '/@/components/Table/src/types/table';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { getalarmrecord, changealarmstatus } from '/@/api/alertRules/index';
  import { ref, h, onMounted, onBeforeUnmount } from 'vue';
  import dayjs from 'dayjs';
  import { useGo } from '/@/hooks/web/usePage';

  const go = useGo();
  let loading = ref<boolean>(false);
  const { hasPermission } = usePermission();
  let searchValue = ref('');
  let isSearch = false;
  // 计时器
  let intervalID: any = '';
  // 表单数据
  let columns: BasicColumn[] = [
    {
      title: '报警编码',
      dataIndex: 'AlarmCode',
      width: 150,
    },
    {
      title: '设备编码',
      dataIndex: 'AssetCode',
      width: 200,
    },
    {
      title: '设备名称',
      dataIndex: 'DeviceName',
      width: 300,
    },
    {
      title: '设备型号编码',
      dataIndex: 'ModelCode',
      width: 250,
    },
    {
      title: '设备型号名称',
      dataIndex: 'ModelName',
      width: 250,
    },
    {
      title: '设备类型',
      dataIndex: 'TypeName',
      width: 300,
    },
    // {
    //   title: '告警名称',
    //   dataIndex: 'AlarmFullName',
    //   width: 300,
    // },
    {
      title: '报警级别',
      dataIndex: 'AlarmLevel_text',
    },
    {
      title: '报警主题',
      dataIndex: 'AlarmTopic',
    },
    {
      title: '报警类型',
      dataIndex: 'AlarmType',
    },
    // {
    //   title: '变量',
    //   dataIndex: 'TagFullName',
    //   width: 300,
    // },
    {
      title: '报警状态',
      dataIndex: 'AlarmStatus_text',
    },
    {
      title: '报警值',
      dataIndex: 'AlarmValue',
    },
    // {
    //   title: '限值',
    //   dataIndex: 'LimitValue',
    // },
    {
      title: '报警时间',
      dataIndex: 'TriggerTime',
    },
    {
      title: '关闭值',
      dataIndex: 'RecoveryValue',
    },
    {
      title: '关闭时间',
      dataIndex: 'RecoveryTime',
    },
    {
      title: '应答时间',
      dataIndex: 'ResponseTime',
    },
    {
      title: '描述',
      dataIndex: 'Description',
    },
  ];
  let actionColumn = {
    width: 200,
    title: '操作',
    dataIndex: 'action',
    // slots: { customRender: 'action' },
  };
  const [registerTable, { reload, getPaginationRef, setPagination }] = useTable({
    title: '',
    api: getalarmrecord,
    immediate: false,
    columns,
    actionColumn: hasPermission('7-1-2-respondAlarm') ? actionColumn : undefined,
    canResize: false,
    showIndexColumn: false,
    striped: true,
    bordered: true,
    fetchSetting: {
      pageField: 'PageNO',
      sizeField: 'PageSize',
      totalField: 'TotalRows',
      listField: 'Rows',
    },
    beforeFetch: () => {
      return [
        {
          SearchValue: isSearch ? searchValue.value : '',
          PageNO: getPaginationRef().current || 1,
          PageSize: getPaginationRef().pageSize || 50,
        },
      ];
    },
    afterFetch: (v) => {
      let levelObj = {
        0: '信息',
        1: '次要',
        2: '一般',
        3: '主要',
        4: '严重',
      };
      let AlarmStatusObj = {
        0: '无',
        1: '告警',
        2: '响应',
        3: '恢复',
      };
      return v.map((item) => {
        item.TriggerTime =
          item.TriggerTime && dayjs(item.TriggerTime).format('YYYY-MM-DD HH:mm:ss');
        item.RecoveryTime =
          item.RecoveryTime && dayjs(item.RecoveryTime).format('YYYY-MM-DD HH:mm:ss');
        item.ResponseTime =
          item.ResponseTime && dayjs(item.ResponseTime).format('YYYY-MM-DD HH:mm:ss');

        item.AlarmLevelCn = levelObj[item.AlarmLevel];
        item.AlarmStatusCn = AlarmStatusObj[item.AlarmStatus];
        return item;
      });
    },
  });
  const { createConfirm, createMessage } = useMessage();
  const { t } = useI18n();
  // 搜索方法
  function onSearch() {
    isSearch = ['', null, undefined].indexOf(searchValue.value) === -1;
    setPagination({
      current: 1,
    });
    reload();
  }
  function handleSet(_record) {
    createConfirm({
      iconType: 'warning',
      okText: '确认',
      title: () => h('span', '温馨提示'),
      content: () => h('span', `是否确认触发应答告警（${_record.AlarmFullName}）`),
      onOk: async () => {
        try {
          await changealarmstatus([_record]);
          createMessage.success(t('layout.setting.operatingTitle'));
          reload();
        } catch (error) {}
      },
    });
  }
  //远程诊断
  function openRouter(_record) {
    go('/dataApplication/alarmManagement/diagnosis');
  }
  // 启动轮询
  function startIntercal() {
    if (intervalID) clearInterval(intervalID);
    intervalID = setInterval(() => {
      onSearch();
    }, 15000);
  }
  onMounted(() => {
    reload();
    startIntercal();
  });
  onBeforeUnmount(() => {
    if (intervalID) clearInterval(intervalID);
  });
</script>

<style lang="less" scoped>
  .p-4-tag {
    width: 100%;
    height: 100%;
    padding: 0px !important;

    .tag {
      position: relative;
      overflow: hidden;
      height: 100%;
      background-color: #fff;
    }
  }
</style>
